import axios, { AxiosRequestConfig } from 'axios'
import { message } from 'ant-design-vue'
import { useCommonStore } from '@/store/common'
import { useUserStore } from '@/store/user'
import router from '@/router'
import { removeToken } from '@/utils/token'

export interface IAxiosRequestConfig extends AxiosRequestConfig {
  loading?: boolean;
  isFile?: boolean;
}

const service = axios.create({ baseURL: '' })

service.interceptors.request.use((config: IAxiosRequestConfig) => {
  const commonStore = useCommonStore()
  const userStore = useUserStore()
  config.loading && commonStore.handleChangeLoading('add')

  if (userStore.token) {
    config.headers.Authorization = userStore.token
  }
  config.headers['Content-Type'] = 'application/json'
  return config
}, error => { Promise.reject(error) })

service.interceptors.response.use((response) => {
  const requestConfig: IAxiosRequestConfig = response.config
  const commonStore = useCommonStore()
  requestConfig.loading && commonStore.handleChangeLoading('sub')
  return response.data
}, error => {
  const commonStore = useCommonStore()
  commonStore.handleChangeLoading('reset')
  // 兼容blob下载出错json提示
  if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
    const reader = new FileReader()
    reader.readAsText(error.response.data, 'utf-8')
    reader.onload = function () {
      const errorMsg = JSON.parse(reader.result as string).message
      message.error(errorMsg, 5000)
    }
    return
  }
  let code = 0
  try {
    code = error.response.data.status
  } catch (e) {
    // do nothing
  }

  if (code === 401) {
    message.warn('登录超时，请重新登录')
    removeToken()
    router.push('/login')
    return
  }

  message.warn(error.response.data.message)
})

export default service
